package org.batch.config.batch.item.reader;

import cn.hutool.core.util.ObjectUtil;
import org.batch.entity.Trading;
import org.batch.mapper.TradingMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.ItemReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

/**
 * Trading数据库数据读取器
 *
 * @author LiKun
 * @StepScope：改Bean的生命周期与Job任务同步
 * @date 2021/9/28 15:13
 */
@StepScope
@Component("tradingJdbcReader")
public class TradingJdbcReader implements ItemReader<Trading> {
    private static final Logger logger = LoggerFactory.getLogger(TradingJdbcReader.class);

    private int counter = 0;
    private List<Trading> memory;

    @Value("#{jobParameters[account]}")
    private volatile String account;

    @Resource
    private TradingMapper tradingMapper;

    @Override
    @Transactional
    public Trading read() throws Exception {
        Trading trading = null;
        if (ObjectUtil.isNull(memory)) {
            memory = tradingMapper.selectByAccount(account);
        }

        try {
            trading = memory.get(counter++);

            logger.info("成功从MySQL中读取数据：{}", trading);
        } catch (Exception e) {
            logger.info("数据库数据已读取完毕");
        }

        return trading;
    }

    @PostConstruct
    public void initialize() {
        logger.info("加载JDBC批处理数据读取器");
    }
}
